import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:studymanage/core/global.dart';
import 'package:studymanage/util/jpush_manager.dart';
import 'package:studymanage/util/request.dart';

import '../home.dart';
import '../update_version.dart';
import 'login.dart';

class Advertisement extends StatefulWidget {
  Advertisement({Key key, this.title,this.type}) : super(key: key);
  //1,正常 ，2不检查更新
  final int type;
  final String title;

  @override
  State<StatefulWidget> createState() {
    return AdvertisementState();
  }
}

class AdvertisementState extends State<Advertisement> {
  Timer _timer;
  int _countdown=3;
  String advert="";
  String version="";
  int updateType = 0;
  bool isNeedUpdate = false; //
  String downUrl ;
  @override
  void initState() {
    //获取广告
    Request().post("/multiapi/open/c208v_start").then((response){
      setState(() {
        advert = response.data['url'];
        _countdown = response.data['second'];
        _timer = Timer.periodic(Duration(milliseconds: 1000), (t) {
          setState(() {
            _countdown-=1;
            if(_countdown==0) {
              t.cancel();
              if(widget.type ==1 ){
                _checkVersion();
              }
            }
          });
        });
      });
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:Container(
        height: MediaQuery.of(context).size.height,
        width: MediaQuery.of(context).size.width,
        child:  Stack(
        children: <Widget>[
          Container(
            height: MediaQuery.of(context).size.height,
            width: MediaQuery.of(context).size.width,
            decoration: BoxDecoration(
              color: Colors.grey,
              image: DecorationImage(
                image:  Image.network(advert).image,
                fit: BoxFit.fill
              )
            ),
          ),
          Positioned(
            top: 30,
            right: 22,
            child:  GestureDetector(
              child: Container(
                width: 91,
                height: 30,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(25)
                ),
                child: Text(_countdown.toString() + " 跳过",style: TextStyle(fontSize: 14,fontWeight: FontWeight.w200),),
              ),
              onTap: (){
                  _checkVersion();
                },
            ),
          ),
        ],
      ),
      ),
    );
  }

  @override
  void dispose() {
    if (_timer != null) {
      // 页面销毁时触发定时器销毁
      _timer.cancel();
    }
    super.dispose();
  }

  _checkVersion() async {
    String version ='';
    await  SharedPreferences.getInstance().then((share) {
     version = share.get("version");
    });
    if(version == DateTime.now().year.toString() + DateTime.now().month.toString() + DateTime.now().day.toString()){
      if(Global.profile.token!=null){
        Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => new Home(Global.profile.userTypeEnum ==1 ? Role.student : Role.teacher)), (Route<dynamic> route) => false);
      }else{
        Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => new Login(1)), (Route<dynamic> route) => false);
      }
      return;
    }
    int appType = 0;
    if(Platform.isIOS){
      appType = 2;
    }
    if(Platform.isAndroid){
      appType = 1;
    }
    PackageInfo.fromPlatform().then((packageInfo) {
      Request()
          .post<Map<String, dynamic>>("/multiapi/open/c181v_version",data: {"version":packageInfo.version,"appType":appType})
          .then((response) {
        if(response.code == 200){
          if (packageInfo.version != response.data['version']) {
            setState(() {
              version = response.data['version'];
              isNeedUpdate = true;
              updateType=response.data['updateType'];
              downUrl = response.data['downUrl'];
            });
            Navigator.of(context).pushAndRemoveUntil(
                MaterialPageRoute(builder: (context) => UpdateVersion(version: version,isNeedUpdate: isNeedUpdate,updateType: updateType,downUrl: downUrl,)),
                    (Route<dynamic> route) => false);
          }else{
            if(Global.profile.token!=null){
              Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => new Home(Global.profile.userTypeEnum ==1 ? Role.student : Role.teacher)), (Route<dynamic> route) => false);
            }else{
              Navigator.of(context).pushAndRemoveUntil(MaterialPageRoute(builder: (context) => new Login(1)), (Route<dynamic> route) => false);
            }
          }
        }
      });
    });
  }
}